'''
Descripttion: 视图函数，后端控制函数
version: python 3.6.2
Author: 刘涛
Date: 2021-04-14 19:29:01
LastEditors: 刘涛
LastEditTime: 2021-05-07 19:04:10
'''
from django.http.response import JsonResponse
from moments.models import Status, WeChatUser, Reply, IMG
from django.shortcuts import redirect, render
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator  # 用于分页
from django.db.models import Q  # 复杂搜索
# from moments import models

# Create your views here.


# 主页
def home(request):
    return render(request, 'homepage.html')


# 用户主页
@login_required
def show_user(request):
    # po = {
    #     'name': 'xiao po',
    #     'motto': 'i love kungfu',
    #     'email': '2@qq.com',
    #     'region': 'Shaanxi',
    #     'pic': 'Po2.jpg'
    # }
    user = WeChatUser.objects.get(user=request.user)
    return render(request, "user.html", {"user": user})


# 广场
@login_required
def show_status(request):
    # statuses = Status.objects.all()
    """
    import pdb
    pdb.set_trace()
    后端调试，加断点信息
    """

    keyword = request.GET.get("keyword")
    page = request.GET.get("page", "1")
    if not keyword:
        statuses = Status.objects.all()  # 全部搜索
    else:
        # Q是复杂搜索
        statuses = Status.objects.filter(Q(text__contains=keyword) | Q(
            user__user__username__contains=keyword))
        # statuses = Status.objects.filter(text__contains=keyword)
        # statuses = Status.objects.filter(user__user__username__contains=keyword)
    p = Paginator(statuses, 2)   # 先展示俩页
    statuses = p.get_page(page)
    for status in statuses:
        status.likes = Reply.objects.filter(status=status, type="0")
        status.comments = Reply.objects.filter(status=status, type="1")
    return render(request, "status.html", {"statuses": statuses,
                                           "keyword": keyword,
                                           "page": int(page),
                                           "page_range": p.page_range})


# 提交分享
@login_required
def submit_post(request):
    user = WeChatUser.objects.get(user=request.user)
    text = request.POST.get('text')   # 获取文本
    uploaded_file = request.FILES.get('pics')  # 获取图片
    if uploaded_file:
        name = uploaded_file.name  # 取出图片名字
        with open("./moments/static/image/{}".format(name), 'wb')as handle:
            # 把图片存入staic的image里
            for block in uploaded_file.chunks():
                handle.write(block)
    else:
        name = ''
    if text:
        status = Status(user=user, text=text, pics=name)
        status.save()
        return redirect('/status')
    return render(request, 'my_post.html')


# 关于
@login_required
def about(request):
    return render(request, 'readme.html')


# 注册
def register_user(request):
    try:
        username = request.POST.get("username")
        email = request.POST.get("email")
        password = request.POST.get("password")
        user = User(username=username, email=email)
        user.set_password(password)
        user.save()
        WeChatUser.objects.create(user=user)
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "注册成功!"

    # 注册完成后，还是返回本页面，采用的是异步刷新技术
    return JsonResponse({"result": result, "message": message})


# 修改个人信息
@login_required
def update_user(request):
    try:
        motto = request.POST.get("motto")
        if motto:
            WeChatUser.objects.filter(user=request.user).update(motto=motto)
        region = request.POST.get("region")
        if region:
            WeChatUser.objects.filter(user=request.user).update(region=region)
        pic = request.POST.get("pic")
        if region:
            WeChatUser.objects.filter(user=request.user).update(pic=pic)
        email = request.POST.get("email")
        if email:
            User.objects.filter(username=request.user).update(email=email)
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "修改成功!"

    # 注册完成后，还是返回本页面，采用的是异步刷新技术
    return JsonResponse({"result": result, "message": message})


# 已购
@login_required
def buy(request):
    IMG.objects.filter(name='bg')
    img = IMG.objects.all()
    return render(request, 'buy.html', {'img': img})


# # 商场
# @login_required
# def mall(request):
#     return render(request, "mall.html")


# 购买
@login_required
def submit_pic(request):
    # user = WeChatUser.objects.get(user=request.user)
    name = request.POST.get('name')   # 获取图片名字
    img = request.POST.get('pic1')  # 获取图片
    if name:
        img = IMG(name=name, img=img)
        img.save()
        return redirect('/buy')
    return render(request, 'mall.html')


# 点赞
@login_required
def like(request):
    user = request.user.username
    status_id = request.POST.get("status_id")

    liked = Reply.objects.filter(author=user, status=status_id, type="0")
    if liked:
        liked.delete()
    else:
        Reply.objects.create(
            author=user, status=Status.objects.get(id=status_id), type="0")
    return JsonResponse({"result": True})


# 评论
@login_required
def comment(request):
    user = request.user.username
    status_id = request.POST.get("status_id")
    at_person = request.POST.get("at_person")
    text = request.POST.get("text")

    Reply.objects.create(author=user, status=Status.objects.get(
        id=status_id), type="1", at_person=at_person, text=text)
    return JsonResponse({"result": True})


# 删除评论
@login_required
def delete_comment(request):
    comment_id = request.POST.get("comment_id")
    Reply.objects.filter(id=comment_id).delete()
    return JsonResponse({"result": True})


# @login_required
# def updateinfo(request):
#     if request.method == 'POST':
#         # img = request.FILES.get('photo')
#         # user = request.FILES.get('photo').name
#         new_img = models.IMG(
#             photo=request.FILES.get('photo'),  # 拿到图片
#             user=request.FILES.get('photo').name  # 拿到图片的名字
#         )
#         new_img.save()  # 保存图片
#         return HttpResponse('上传成功！')

#     return render(request, 'buy.html')
